package com.eascs.ant.user.controller;

import javax.inject.Inject;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.eascs.ant.common.entity.EntityUtil;
import com.eascs.ant.common.form.IdForm;
import com.eascs.ant.user.entity.Team;
import com.eascs.ant.user.entity.TeamItem;
import com.eascs.ant.user.entity.TeamUpdate;
import com.eascs.ant.user.form.InsertTeamItemForm;
import com.eascs.ant.user.form.SaveTeamForm;
import com.eascs.ant.user.service.TeamItemService;
import com.eascs.ant.user.service.TeamService;
import com.eascs.common.util.ObjectUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;

@RestController
public class TeamRestController extends BaseRestController {

	@Inject
	private TeamService teamService;

	@Inject
	private TeamItemService teamItemService;

	@RequestMapping("/user/team/getTeamEdit")
	public HtmlRestResult getTeamEdit(IdForm idForm) {
		Team team = null;
		if (StringUtil.hasText(idForm.getId())) {
			team = teamService.getTeamById(idForm.getId());
		} else {
			team = new Team();

		}
		ViewContext.put("team", team);
		return HtmlRestResult.popHtmlFragment("/user/team/getTeamEdit");
	}

	@RequestMapping("/user/team-item/getAddTeamItemView")
	public HtmlRestResult getAddTeamItemView(IdForm idForm) {
		Team team = teamService.getTeamById(idForm.getId());
		ViewContext.put("team", team);
		return HtmlRestResult.popHtmlFragment("/user/team/getAddTeamItemView");
	}

	@RequestMapping("/user/team-item/insert")
	public BaseRestResult<String> insertTeamItem(InsertTeamItemForm insertTeamItemForm) {
		TeamItem teamItem = new TeamItem();
		ObjectUtil.copySimpleProperties(insertTeamItemForm, teamItem);
		EntityUtil.initInsertEntity(teamItem);
		this.teamItemService.insertTeamItem(teamItem);
		return BaseRestResult.refresh();
	}

	@RequestMapping("/user/team-item/delete")
	public BaseRestResult<String> deleteTeamItem(IdForm idForm) {
		teamItemService.deleteTeamItem(idForm.getId());
		return BaseRestResult.refresh();
	}

	@RequestMapping("/user/team/save")
	public BaseRestResult<String> saveTeam(SaveTeamForm saveTeamForm) {
		if (StringUtil.hasText(saveTeamForm.getId())) {
			TeamUpdate teamUpdate = new TeamUpdate();
			ObjectUtil.copySimpleProperties(saveTeamForm, teamUpdate);
			EntityUtil.initUpdateEntity(teamUpdate);
			this.teamService.updateTeam(teamUpdate);
		} else {
			Team team = new Team();
			ObjectUtil.copySimpleProperties(saveTeamForm, team);
			EntityUtil.initInsertEntity(team);
			this.teamService.insertTeam(team);

		}
		return BaseRestResult.refresh();
	}

	@RequestMapping("/user/team/delete")
	public BaseRestResult<String> deleteTeam(IdForm idForm) {
		this.teamService.deleteTeam(idForm.getId());
		return BaseRestResult.refresh();
	}
}
